package cm.tl.pms.util.fileParser.excel;

import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class ExcelExportUtil {

    public static void setExcelResponseHeader(HttpServletResponse response, String fileName) throws IOException {
        // 设置文件名为UTF-8编码，避免中文乱码
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 设置ContentDisposition头部信息，指定文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
    }

    public static void exportExcel(HttpServletResponse response, String fileName, Class<?> clazz, String sheetName, List<?> dataList) throws IOException {
        setExcelResponseHeader(response, fileName);

        // 使用 EasyExcel 写入数据，并设置列宽
        EasyExcel.write(response.getOutputStream(), clazz)
                .excelType(com.alibaba.excel.support.ExcelTypeEnum.XLSX)
                .sheet(sheetName)
                // 设置列宽 自定义
                .registerWriteHandler(new FixedWidthColumnStyleStrategy())
                .doWrite(dataList);
    }
}